﻿package com.tomvian.maths.areas
{
	import com.tomvian.maths.Vector2D;
	
	/**
	 * MultiArea
	 * @author Thomas Vian
	 */
	public class MultiArea extends Area
	{
		//--------------------------------------------------------------------------
		//
		//  Properties
		//
		//--------------------------------------------------------------------------
		
		protected var _areas:Vector.<Area>;
		protected var _areasNum:uint;
		
		//--------------------------------------------------------------------------
		//
		//  Constructor
		//
		//--------------------------------------------------------------------------
		
		public function MultiArea(areas:Array)
		{
			_areas = Vector.<Area>(areas);
			_areasNum = _areas.length;
			
			area = 0;
			for (var i:uint = 0; i < _areasNum; i++) area += _areas[i].area;
		}
		
		//--------------------------------------------------------------------------
		//
		//  Methods
		//
		//--------------------------------------------------------------------------
		
		override public function contains(vector:Vector2D):Boolean 
		{ 
			for (var i:uint = 0; i < _areasNum; i++)
			{
				if(_areas[i].contains(vector))  return true
			}
			
			return false;
		}
		
		override public function random():Vector2D 
		{
			var randArea:Number = Math.random() * area;
			
			var totalSoFar:Number = 0;
			
			for(var i:uint = 0; i < _areasNum; i++)
			{
				var a:Area = _areas[i];
				totalSoFar += a.area;
				if(totalSoFar >= randArea) return a.random();
			}
		}
	}
}